import * as log4js from 'log4js';
import config from '../config';
// 配置log4.js
log4js.configure({
	appenders: {
        error: {
            type: 'file',           //日志类型
            category: 'errLogger',    //日志名称
            filename: __dirname + config.log.errorPath, //日志输出位置，当目录文件或文件夹不存在时自动创建
            maxLogSize: 104800, // 文件最大存储空间
            backups: 100  //当文件内容超过文件存储空间时，备份文件的数量
        },
        response: {
            type: 'dateFile',
            category: 'resLogger',
            filename: __dirname + config.log.responsePath,
            pattern: 'yyyy-MM-dd.log', //日志输出模式
            alwaysIncludePattern: true,
            maxLogSize: 104800,
            backups: 100
        }
    },
	categories: {
        error: {appenders: ['error'], level: 'error'},
        response: {appenders: ['response'], level: 'info'},
        default: { appenders: ['response'], level: 'info'}
    },
    
})

const errorLogger = log4js.getLogger('error'); //categories的元素
const resLogger = log4js.getLogger('response');

const formatError = (ctx:any, err:any,costTime:any) => {
    let method = ctx.method
    let url = ctx.url
    let body = ctx.request.body
    let userAgent = ctx.header.userAgent
    return {method, url, body, costTime, err}
}
const formatRes = (ctx:any,costTime:any) => {
    let method = ctx.method
    let url = ctx.url
    let body = ctx.request.body
    let response = ctx.response
    return {method, url, body, costTime, response}
}

const logger:any = {
	logError : function (ctx: any, error: any, resTime: any) {
		if (ctx && error) {
			errorLogger.error(formatError(ctx, error, resTime));
		}
	},
	logResponse : function (ctx: any, resTime: any) {
		if (ctx) {
			resLogger.info(formatRes(ctx, resTime));
		}
	}
};

const loggerMiddleware = async (ctx:any, next:any) => {
// 请求开始时间
  const start = new Date();
  await next();
  // 结束时间
  const ms:number = new Date().getTime() - start.getTime();
    // 打印出请求相关参数
  const remoteAddress = ctx.headers['x-forwarded-for'] || ctx.ip || ctx.ips ||
    (ctx.socket && (ctx.socket.remoteAddress || (ctx.socket.socket && ctx.socket.socket.remoteAddress)));
  let logText = `${ctx.method} ${ctx.status} ${ctx.url} 请求参数： ${JSON.stringify(ctx.request.body)} 响应参数： ${JSON.stringify(ctx.body)} - ${remoteAddress} - ${ms}ms`
  logger.logResponse(ctx, ms);
};

export {
	logger,
	loggerMiddleware
};